package com.sftz.framework.mvc.filter;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.nutz.log.Log;
import org.nutz.log.Logs;

import com.uxuexi.core.common.util.Util;

/**
 * 请求路径过滤器，协助找出不符合规范的请求路径
 * <p>
 *
 * @author   朱晓川
 * @Date	 2018年3月22日 	 
 */
public class RequestPathFilter implements Filter {

	private static final Log log = Logs.get();

	private static final String STATIC_REGEX = ".*?\\.(css|js|ico|png|jpg|jpeg|gif|bmp|swf|map)";

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//do nothing
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {

		HttpServletRequest req = (HttpServletRequest) request;

		//获取请求路径，如果不是以.html结尾则输出日志(TODO 图片,css,js路径都打印出来了-_-)
		String reqPath = req.getServletPath();

		if (!Util.isEmpty(reqPath) && !reqPath.endsWith(".html") && !reqPath.endsWith(".jsp")) {
			//如果不是静态资源
			Pattern p = Pattern.compile(STATIC_REGEX, Pattern.CASE_INSENSITIVE);
			if (!p.matcher(reqPath).matches()) {
				log.info("请求地址无效,不是以.html或jsp结尾:" + reqPath);
			}
		}
		chain.doFilter(request, response);

	}

	@Override
	public void destroy() {
		//do nothing

	}

}